﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SQLite;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Linq;
using LiteQuery.Common;

namespace LiteQuery
{
    public partial class FormMain : Form
    {
        FuncPanelHelper.ConfigLoader configLoader;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            InitPanels();
            this.lblVersion.Text = "当前版本: "+System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString();
            this.lblVersion.Text += " | 数据库: "+configLoader.FuncConfig.Config.DBName;
        }

        private void InitPanels()
        {
            configLoader = new FuncPanelHelper.ConfigLoader("config.xml");
            if (configLoader == null)
            {
                Common.WinForm.ShowEror("配置文件初始化失败");
                return;
            }
            var cfg = configLoader.FuncConfig;
            if (cfg.Config.AutoCreateDB)
            {
                cfg.Config.DataSource = string.Format(cfg.Config.DataSource, cfg.Config.DBName);
                if (!TestConnection())
                    return;
            }

            if (cfg.Funcs.Count == 0)
                return;

            tabContainer.TabPages.Clear();
            foreach (Entities.Func item in cfg.Funcs.OrderBy(x=>x.Index))
            {
                AddTabPage(item, configLoader.FuncConfig.Config);
            }
        }

        bool TestConnection()
        {
            try
            {
                using (SQLiteConnection conn = new SQLiteConnection(configLoader.FuncConfig.Config.DataSource))
                {
                    conn.Open();
                    // 创建日志表
                    SqlFuncHelper.AsposeHelper.CreateLogDB(configLoader.FuncConfig.Config.DataSource);

                    conn.Close();
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return false;
            }
        }

        bool AddTabPage(Entities.Func config, Entities.Config dbcfg)
        {
            try
            {
                // 创建面板容器
                var page = new TabPage(config.Name);
                // 添加数据面板
                var panel = new Controls.FuncPanel(config, dbcfg);
                panel.Dock = DockStyle.Fill;
                page.Controls.Add(panel);
                tabContainer.TabPages.Add(page);
                return true;
            }
            catch {
                return false;
            }
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            var page = tabContainer.SelectedTab;
            var panel = page.Controls[0] as Controls.FuncPanel;
            panel.Query();
        }

        private void 根据模板创建数据表ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var diag = new OpenFileDialog() {
                Multiselect=false,
                Title="选择数据表模板"
            };
            if (diag.ShowDialog() == DialogResult.OK)
            {
                var ret = SqlFuncHelper.AsposeHelper.CreateDBFromTemplate(configLoader.FuncConfig.Config.DataSource, configLoader.FuncConfig.Config.TableName, diag.FileName);
                if (ret.Item1)
                    Common.WinForm.ShowInfo("数据表创建出成功");
                else
                    Common.WinForm.ShowEror("数据表创建失败: "+ret.Item2.Message);
            }
        }

        private void 导入ExcelToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var diag = new OpenFileDialog()
            {
                Multiselect = false,
                Title = "选择数据表模板"
            };
            if (diag.ShowDialog() == DialogResult.OK)
            {
                var ret = SqlFuncHelper.AsposeHelper.ReadExcelSheetOneToDataTable(configLoader.FuncConfig.Config.DataSource, configLoader.FuncConfig.Config.TableName, diag.FileName);
                if (ret.Item1)
                    Common.WinForm.ShowInfo("数据导入成功");
                else
                    Common.WinForm.ShowEror("数据导入失败: "+ret.Item2.Message);
            }
        }

        private void 初始化数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var diag = new OpenFileDialog()
            {
                Multiselect = false,
                Title = "选择数据源"
            };
            if (diag.ShowDialog() == DialogResult.OK)
            {
                var ret = SqlFuncHelper.AsposeHelper.CreateAndInsert(configLoader.FuncConfig.Config.DataSource, configLoader.FuncConfig.Config.TableName, diag.FileName);
                if (ret.Item1)
                    Common.WinForm.ShowInfo("数据初始化成功");
                else
                    Common.WinForm.ShowEror("数据初始化失败: "+ret.Item2.Message);
            }
        }

        private void 装载一批数据ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var diag = new OpenFileDialog()
            {
                Multiselect=true,
                Title = "选择数据源"
            };
            if (diag.ShowDialog() == DialogResult.OK && diag.FileNames.Length>0)
            {
                Common.WinForm.ShowToast(this, "装载中, 请稍后...");
                var ret = SqlFuncHelper.AsposeHelper.CreateAndInsert(configLoader.FuncConfig.Config.DataSource, configLoader.FuncConfig.Config.TableName, diag.FileNames);
                if (ret.Item1)
                    Common.WinForm.ShowInfo("数据初始化成功");
                else
                    Common.WinForm.ShowEror("数据初始化失败: "+ret.Item2.Message);
                Common.WinForm.HidToast();

                System.Threading.Thread.Sleep(100);
                Common.WinForm.ShowToast(this, "查询中, 请稍后...");
  
                btnQuery.PerformClick();
                Common.WinForm.HidToast();
            }
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var diag = new SaveFileDialog()
            {
                Title = "选择导出位置",
                DefaultExt = ".xls",
                Filter = "Excel97-2003(*.xls)|*.xls|Excel2007(*.xlsx)|*.xlsx",
                FilterIndex = 0
            };
            if (diag.ShowDialog() == DialogResult.OK)
            {
                var page = tabContainer.SelectedTab;
                var panel = page.Controls[0] as Controls.FuncPanel;
                panel.Export(diag.FileName);
            }
        }

        private void 导入文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var form = new ImportGuide();
            if (form.ShowDialog() == DialogResult.OK)
            {
                Common.WinForm.ShowToast(this, "导入中, 请稍后...");

                var errList = new List<string>();
                foreach (LiteQuery.Controls.FileRowPanel item in form.Rows)
                {
                    var ret = SqlFuncHelper.AsposeHelper.CreateAndInsert(configLoader.FuncConfig.Config.DataSource, item.TableName, item.FullFileName);
                    if (!ret.Item1)
                        errList.Add(item.FullFileName+" => "+ret.Item2.Message);
                }

                if (errList.Count == 0)
                    Common.WinForm.ShowInfo("导入成功, 请参考配置模板[config.xml], 创建相应的查询面板.");
                else
                    Common.WinForm.ShowEror("导入失败\r\n"+string.Join("\r\n",errList.ToArray()));

                Common.WinForm.HidToast();
            }
        }
    }
}
